
import { getUserList, addUser, updateUser, deleteUser, uploadImg, isExistUser, handleMenu, handleRole, getISVUserList } from '@/api/user'
import { deepClone } from "@/utils"
import { getAllRoleList, getDialogRoleList } from "@/api/role"
import { getRoutes } from "@/api/menu"
import { GetAllOrgList } from "@/api/org"
import InfoUpload from "@/views/user/infoUpload"
import ISVInfoUpload from "@/views/user/ISVInfoUpload"
import SGMWInfoUpload from "@/views/user/SGMWInfoUpload"
import JKInfoUpload from "@/views/user/JKInfoUpload"
import waves from "@/directive/waves" // Waves directive
import { GetDictionaryByPCode } from '@/api/dictionary'
import { reqGetAreaCitys } from "@/api/areacity";

const defaultUser = {
  UserId: '',
  AccountStatus: '',
  Birthday: '',
  CreateTime: '',
  Company: '',
  Creater: '',
  Department: '',
  Email: '',
  HeadPhoto: '',
  ShowHeadPhoto: '',
  LoginName: '',
  ModifyTime: '',
  Modify: '',
  MobilePhone: '',
  Position: '',
  Remark: '',
  UserName: '',
  UserType: '',
  OrgName: '',
  OrgCode: '',
  OfficeTel: '',
  RegisterDevice: '',
  Sex: '保密',
  Password: '',
  ConfirmPassword: '',
  RoleIdList: [],
  MenuIdList: [],
  HalfMenuIdList: []
}
export default {
  components: { InfoUpload, SGMWInfoUpload, ISVInfoUpload, JKInfoUpload },
  directives: { waves },
  data() {
    var validatePass = (rule, value, callback) => {
      var myreg = /(?=^.{7,18}$)(?=(?:.*?\d))(?=.*[a-z])(?=(?:.*?[A-Z]))(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&.,]*$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!myreg.test(value)) {
        callback(new Error('请包涵大小字母、数字以及!@.符号'));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      var myreg = /(?=^.{7,18}$)(?=(?:.*?\d))(?=.*[a-z])(?=(?:.*?[A-Z]))(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&.,]*$/;
      if (value === '') {
        callback(new Error('请确认密码'));
      } else if (!myreg.test(value)) {
        callback(new Error('请包涵大小字母、数字以及!@.符号'));
      } else if (value !== this.user.Password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var checkPhone = (rule, value, callback) => {
      var myreg = /^[1][0-9]{10}$/;
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!myreg.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };
    var checkEmail = (rule, value, callback) => {
      var myreg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
      if (value === null || value === '') {
        callback();
      } else if (!myreg.test(value)) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    };
    var checkLoginName = (rule, value, callback) => {
      var id = this.user.UserId
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        this.isExistUser(id, value).then((res) => {
          if (res)
            callback(new Error('用户名已经存在，请重新输入'));
          else
            callback();
        });
      }
    };

    return {
      userViewModel: {
        page: 1,
        pageSize: 10,
        total: 0,
        UserName: '',
        LoginName: '',
        MobilePhone: '',
        AgentNumber: '',
        Unumber: '',
        SGMWRecordJob: '',
        AreaCode: '',
        ProvinceCode: '',
        CityCode: '',
        UserType: 'USER',
        OrderBy: 'CreateTime',//排序字段
        SortDir: '' //是否升序
      },
      query: {
        Page: 1,
        PageSize: 10000,
        Total: 0,
        OrderBy: "AreaCode",
        IsAsc: true,
        TypeLevel: -1,
        AreaCode: -1,
        AreaName: "",
        ProvinceCode: -1,
        ProvinceName: "",
        CityCode: -1,
        CityName: ""
      },
      temp: {
        ID: null,
        AreaCode: 101,
        ProvinceCode: 10001,
        CityCode: 10000001,
        DealerCode: "",
        BusinessType: "",
        DealerName: "",
        BusinessNature: "",
        ManagementCode: "",
        ManagementName: "",
        InvestCode: "",
        InvestName: ""
      },
      views: [],
      areaCitys: [],
      areaDatas: [],
      provinceDatas: [],
      cityDatas: [],
      areaTempDatas: [],
      provinceTempDatas: [],
      cityTempDatas: [],
      dialogVisible: false,
      dialogRoleVisible: false,
      SGMWVisible: false,
      jkVisible: false,
      ISVVisible: false,
      dialogType: '',
      randomNum: '',
      tabs: [],
      activeName: 'USER',
      user: Object.assign({}, defaultUser),
      userTree: Object.assign({}, defaultUser),
      userRole: Object.assign({}, defaultUser),
      SGMWuserList: [],
      JXSuserList: [],
      ISVuserList: [],
      JKuserList: [],
      routes: [],
      roles: [],
      tempMark: false,
      allOrg: [],//全部组织列表
      roleList: [],
      typeOptions: [],
      sexList: ['保密', '男', '女'],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: '',
      loading: true,
      dialogTreeVisible: false,
      dialogJXSVisible: false,
      dialogJKVisible: false,
      upDialogFormVisible: false,
      defaultRoleProps: {
        children: "children",
        label: "RoleName"
      },
      defaultProps: {
        children: "children",
        label: "title"
      },
      rules: {
        UserName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ],
        LoginName: [
          { required: true, message: "请输入登录名", trigger: "blur" }
          // { validator: checkLoginName, trigger: 'blur' }
        ],
        Password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: 'blur' }
        ],
        ConfirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: validatePass2, trigger: 'blur' }
        ],
        MobilePhone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: 'blur' }
        ],
        Email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        OrgCode: [
          { required: true, message: "请选择学校", trigger: "blur" }
        ],
      },
      UserTypeList: [
        { key: 'USER', title: '用户' },
        { key: 'TEACHER', title: '讲师' },
        { key: 'STUDENT', title: '学生' }
      ]
    }
  },
  computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
    routesData() {
      return this.routes;
    }
  },
  created() {  // 实例创建完成后执行的代码
    this.queryUser();
    // this.getAllRoleList();
    this.getRoles();
    this.searchInit()
    // this.getRoutes();
    this.getAllOrgList();
    this.actionUrl = this.apiPre + '/Upload/UploadAttachment'
  },
  methods: {
    // 区、省、市数据初始化
    async searchInit() {
      let res = await reqGetAreaCitys(this.query);
      if (res.code === 200) {
        this.areaCitys = res.data.Items;
        this.areaDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
        this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
        this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);

        this.areaTempDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
        if (!this.isEidt) this.temp.AreaCode = this.areaTempDatas[0].AreaCode;
      }
    },
    // 区域下拉搜索
    AreaSearch() {
      if (this.userViewModel.AreaCode) {
        this.provinceDatas = this.areaCitys.filter(
          s => s.TypeLevel === 2 && s.AreaCode === this.userViewModel.AreaCode
        );
        this.cityDatas = this.areaCitys.filter(
          s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
        );
      } else {
        this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
        this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
      }
      this.userViewModel.ProvinceCode = null;
      this.userViewModel.CityCode = null;
      this.queryUser();
    },
    // 省份下拉搜索
    ProvinceSearch() {
      if (this.userViewModel.ProvinceCode) {
        this.cityDatas = this.areaCitys.filter(
          s =>
            s.TypeLevel === 3 && s.ProvinceCode === this.userViewModel.ProvinceCode
        );
      } else {
        if (this.userViewModel.AreaCode)
          this.cityDatas = this.areaCitys.filter(
            s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
          );
        else this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
      }
      this.userViewModel.CityCode = null;
      this.queryUser();
    },
    // 城市下拉搜索
    CitySearch() {
      this.queryUser();
    },
    async getTabList() {
      var res = await GetDictionaryByPCode("UserType")
      if (res && res.data) {
        this.tabs = res.data
      }
    },
    async getAllOrgList() {
      const res = await GetAllOrgList();
      this.typeOptions = deepClone(res.data.OrgItems);
      this.typeOptions.unshift({ org_code: '', org_name: '全部' })
      this.allOrg = res.data.OrgItems;
    },
    async getRoles() {
      const res = await getDialogRoleList();
      this.roles = res.data.Items;
    },
    async getRoutes() {
      const res = await getRoutes();
      this.routes = res.data;
    },
    async getUserList(userViewModel) {
      this.loading = true;
      var res = await getUserList(userViewModel);
      if (res.data) {
        this.userViewModel.total = res.data.TotalCount;
        this.SGMWuserList = res.data.UserItems;
      }

      this.loading = false;
    },
    async getAllRoleList() {
      const res = await getAllRoleList();
      if (res.data) {
        this.roleList = res.data;
      }
    },
    async isExistUser(id, loginName) {
      const res = await isExistUser(id, loginName);
      this.tempMark = res.data
      return res.data
    },
    queryUser() {
      this.userViewModel.page = 1;
      this.getUserList(this.userViewModel);
    },
    refreshUser() {
      this.userViewModel.UserName = '';
      this.userViewModel.LoginName = '';
      this.userViewModel.MobilePhone = '';
      this.userViewModel.OrgCode = '';
      this.userViewModel.OrgName = '';
      this.userViewModel.AreaCode = '';
      this.userViewModel.ProvinceCode = '';
      this.userViewModel.CityCode = '';
      this.userViewModel.Unumber = '';
      this.userViewModel.AgentNumber = '';

      this.userViewModel.page = 1;
      this.getUserList(this.userViewModel);
    },
    sortChange(data) {
      const { prop, order } = data
      console.log(data)
      this.userViewModel.OrderBy = prop
      if (prop == null || prop == "")
        this.userViewModel.OrderBy = "UserID"
      if (order === 'ascending') {
        this.userViewModel.SortDir = 'asc'
      } else {
        this.userViewModel.SortDir = 'desc'
      }
      this.queryUser()
    },
    lastPage(val) {
      this.userViewModel.page = val;
    },
    nextPage(val) {
      this.userViewModel.page = val;
    },
    handleSizeChange(val) {
      this.userViewModel.pageSize = val;
      this.getUserList(this.userViewModel);
    },
    handleCurrentChange(val) {
      this.userViewModel.page = val
      this.getUserList(this.userViewModel)
    },
    handleAdd() {
      this.user = Object.assign({}, defaultUser)
      this.user.UserType = this.userViewModel.UserType
      this.$nextTick(() => {
        this.$refs['user'].clearValidate() //清空上次的错误验证提示
      })
      this.dialogType = 'new';
      this.dialogVisible = true;
    },
    handleEdit(scope) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      this.user = deepClone(scope.row);
      var date = new Date(1900, 1, 1)
      var b = new Date(this.user.Birthday)
      if (b < date)
        this.user.Birthday = ''
      this.$nextTick(() => {
        this.$refs['user'].clearValidate() //清空上次的错误验证提示
      });
    },
    handleView(scope) {
      this.dialogJXSVisible = true;
      this.user = deepClone(scope.row);
    },
    handleJKView(scope) {
      this.dialogJKVisible = true;
      this.user = deepClone(scope.row);
    },
    async confirmUser() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs['user'].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      const isEdit = this.dialogType === 'edit';
      var res
      if (isEdit) {
        res = await updateUser(this.user);
      } else {
        res = await addUser(this.user)
        this.userViewModel.page = 1
      }
      if (res && res.code == 200) {
        this.getUserList(this.userViewModel);
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      }
      // else {
      //   this.$notify({
      //     title: "失败",
      //     type: "error",
      //     message: res.message
      //   });
      // }
    },
    handleDelete({ $index, row }) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteUser(row.UserId);
          this.$notify({
            title: "成功",
            type: "success",
            message: "操作成功!"
          });
          this.getUserList(this.userViewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleAvatarSuccess(res, file) {//图片上传成功响应方法
      this.user.HeadPhoto = res.data.SaveUrl
      this.user.ShowHeadPhoto = res.data.DownloadUrl
    },
    beforeAvatarUpload(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      if (!isLt2M) {
        this.$notify({
          title: "失败",
          message: "上传头像图片大小不能超过 5MB!",
          type: "error",
          duration: 3000
        });
        return false
      }
      return true
    },
    handleRole(scope) {
      this.dialogRoleVisible = true
      this.userRole = deepClone(scope.row);
      this.$nextTick(() => {
        this.$refs.uRole.setCheckedKeys(this.userRole.RoleIdList);
      });
    },
    async confirmRole() {
      const checkedKeys = this.$refs.uRole.getCheckedKeys();
      this.userRole.RoleIdList = checkedKeys;
      await handleRole(this.userRole)
      this.queryUser()
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
      this.dialogRoleVisible = false
    },
    handleMenu(scope) {
      this.dialogTreeVisible = true;
      this.userTree = deepClone(scope.row);
      this.$nextTick(() => {
        this.$refs['userTree'].clearValidate() //清空上次的错误验证提示
        this.$refs.tree.setCheckedKeys(this.userTree.MenuIdList);
      });
    },
    async confirmTree() {
      // 获取选中节点id
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      this.userTree.MenuIdList = checkedKeys;

      // 获取半选中节点id
      const halfkeys = this.$refs.tree.getHalfCheckedKeys();
      this.userTree.HalfMenuIdList = halfkeys;

      await handleMenu(this.userTree);
      this.queryUser()
      this.dialogTreeVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },

    //---------------------数据导入
    handleUpload() {
      this.randomNum = Math.random() * 997597 + ''
      this.upDialogFormVisible = true;
    },
    handlesgmwUpload() {
      this.randomNum = Math.random() * 997593 + ''
      this.SGMWVisible = true;
    },
    handleisvUpload() {
      this.randomNum = Math.random() * 997537 + ''
      this.ISVVisible = true;
    },
    handlejkUpload() {
      this.randomNum = Math.random() * 937597 + ''
      this.jkVisible = true;
    },
    closeupDialog() {
      this.upDialogFormVisible = false;
      this.refreshUser();
    },
    closePlatDialog() {
      this.SGMWVisible = false;
      this.refreshUser();
    },
    closeISVVisible() {
      this.ISVVisible = false
      this.refreshUser()
    },
    closejkDialog() {
      this.jkVisible = false
      this.refreshUser();
    },
    handleClick(tab, event) {
      this.userViewModel.UserType = this.activeName
      this.userViewModel.page = 1
      this.refreshUser()
    }
  }
}